<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script src="./lib/axios.js"></script>
    <script>
      // 方法名 2秒之后成功
      function delay2() {
        // 返回Promise对象
        return new Promise(resolve => {
          // 延迟2秒钟 成功
          setTimeout(() => {
            resolve('我成功啦😁')
          }, 2000)
        })
      }

      /*
        1. async 写在声明函数的位置
        2. await 写在async修饰的函数内部
        3. await后面跟上Promise对象
        4. await 等待后面的Promise对象 成功(.then)
        5. 让代码写起来 和同步代码 一样
      */
      async function asyncCall() {
        console.log('calling')
        const result = await delay2()
        console.log(result)
        const result2 = await delay2()
        console.log(result2)
        const result3 = await delay2()
        console.log(result3)
        console.log('bottom')
      }
      // asyncCall()

      // 跟机器人聊天
      /*
        1. await 放在async修饰的函数种
        2. await要跟上Promise对象
        3. await 等待Promise 成功,并获取then中的值,赋值给左边的变量
      */
      async function chatRobot() {
        const res1 = await axios({ url: 'http://ajax-api.itheima.net/api/robot', params: { spoken: '肚子饿了吗?' } })
        console.log('res1:', res1.data.data.info.text)
        const res2 = await axios({ url: 'http://ajax-api.itheima.net/api/robot', params: { spoken: '准备吃点啥呢?' } })
        console.log('res2:', res2.data.data.info.text)
        const res3 = await axios({ url: 'http://ajax-api.itheima.net/api/robot', params: { spoken: '要不要一起吃饭?' } })
        console.log('res3:', res3.data.data.info.text)
      }
      chatRobot()
    </script>
  </body>
</html>
